list gMenu;
list gMenu2;
list gBasicMenu =["<<","END",">>"];
string gMenuPrefix="DV_MAIN_";
integer gMenuLink =1337;
key ToucherID;
integer gDemon =1338;
integer gVic =1329;
integer gPlugin =1339;
integer channel_dialog;
integer listen_id;
string msg ="Main Menu for Devices\nVersion 0.1 Beta";
list objectKey=[];
integer range =10;
integer gPage;
integer attachment = TRUE;
integer relaychannel = -1812221819;
string cmdname;
string ping;
key victim=NULL_KEY;
key locker=NULL_KEY;

list pageMenu(list in ,integer page)
{
	list out;
	integer maxpages =llGetListLength(in)/9;
	page = (page)%(maxpages+1);
	out =["<<"," ",">>"];
	integer _listcount =(page *9)+9;
	integer _i=_listcount-9;
	
	for (_i;_i<_listcount;_i++)
	{
		if(_i<=llGetListLength(in)&&llList2String(in,_i)!="")
		out+=llList2String(in,_i);
	}
	return out;
}

makeMenu()
{
    integer _Scripts = llGetInventoryNumber(INVENTORY_SCRIPT); 
    if (_Scripts == 1)
    {
        llOwnerSay ("No other Scripts inside");
    }
    else if (_Scripts > 1)
    {
        integer i=0;
        gMenu2=[];

        while(i<_Scripts)
        {
            string _Name;
            _Name= llGetInventoryName(INVENTORY_SCRIPT, i);
            if(llGetSubString(_Name, 0, llStringLength(gMenuPrefix)-1) ==gMenuPrefix )
            {
                gMenu2 +=llGetSubString(_Name,llStringLength(gMenuPrefix),llStringLength(_Name));
            }
            i++; 
        }
        gMenu2+=["Free","Lock"];
    }
    llMessageLinked(LINK_THIS, gDemon, "device", NULL_KEY);
    cmdname = (string)llGetKey();
}

displayMenu()
{
    channel_dialog = ( 1 * (integer)("0x"+llGetSubString((string)llGetKey(),-5,-1)) );
	listen_id = llListen( channel_dialog, "", NULL_KEY, "");
    llDialog(ToucherID, msg,gMenu, channel_dialog);
    llSetTimerEvent(45.0);
}

llRlvSay(string command)
{
	if(attachment==TRUE)
	{
		llOwnerSay("@"+command);
	}
	else
	{
		llSay(relaychannel,cmdname + "," + (string)victim  + "," + "@"+command);
	}
}

llRlvSay2(string command)
{
	if(attachment==TRUE)
	{
		llOwnerSay("@"+command);
	}
	else
	{
		llSay(relaychannel,cmdname + "," + (string)victim  + "," +command);
	}
}

list ListItemReplace(list mylist,string element_old, string element_new) 
{
    integer placeinlist = llListFindList(mylist, [element_old]);
    list newlist = llListReplaceList(mylist, [element_new], placeinlist, placeinlist);
    return newlist;
}

default {
    state_entry() 
    {
    	ping = "ping," + (string)llGetKey() + ",ping,ping";
        llListen(relaychannel, "", NULL_KEY, ping);
        makeMenu(); 
    }
    
    listen(integer channel, string name, key id, string message)
    {
    	if (channel == relaychannel)
        {
            if (message == ping && victim == NULL_KEY)
            {
                string pong = "ping," + (string)llGetOwnerKey(id) + ",!pong";
                llSay(relaychannel, pong);
            }
        }
    	if(channel==channel_dialog)
    	{
    		llListenRemove(listen_id);
			llSetTimerEvent(0.0);
			if(message=="<<")
	  		{
	  			gPage--;
				integer maxpages =llGetListLength(gMenu)/9;
				if(gPage<0)
				{
					gPage = maxpages;
				}
				displayMenu();
	  		}
	  		else if(message==">>")
	  		{
	  			gPage++;
	  			displayMenu();
	  		}
	  		else if(message=="Lock")
	  		{
	  			gMenu2=ListItemReplace(gMenu2,"Lock","Unlock");
	  			gMenu=gMenu2;
	  			locker=ToucherID;
	  		}
	  		else if(message=="Unlock")
	  		{
	  			gMenu2=ListItemReplace(gMenu2,"Unlock","Lock");
	  			gMenu=gMenu2;
	  			locker=NULL_KEY;
	  		}
	  		else if(message=="Free")
	  		{
	  			llRlvSay("unsit=y");
	  			llRlvSay("unsit=force"); 
	  			locker=NULL_KEY;
	  			llMessageLinked(LINK_THIS, gPlugin, "RESET", NULL_KEY);
	  			llListenRemove(listen_id);
    			llSetTimerEvent(0.0);
	  		}
	  		else if(message=="End")
	  		{
	  			llListenRemove(listen_id);
    			llSetTimerEvent(0.0);
	  		}
	  		else if(~llListFindList(gMenu2, (list)message))
	  		{
	  			llListenRemove(listen_id);
    			llSetTimerEvent(0.0);
    			llMessageLinked(LINK_THIS, gMenuLink, gMenuPrefix+message, ToucherID);
	  		}
	  		else if(~llListFindList(gMenu, (list)message))
			{
				string tempvictim = llList2String(objectKey, (integer)message);
				if(victim==NULL_KEY);
				{
					string _objectKey =(string)llGetKey();
					string _command = "@sit:"+_objectKey+"=force";
					llSay(relaychannel,cmdname + "," + (string)tempvictim  + "," +_command);
				}
			}
    	}
    }
    
    changed(integer change)
    {
         if (change & CHANGED_INVENTORY)
         { 
             makeMenu();
         }
         if (change & CHANGED_LINK)
        {
            key newav = llAvatarOnSitTarget();
            if (newav != NULL_KEY)
            {
                victim = newav;
                locker=ToucherID;
                llMessageLinked(LINK_THIS, gVic, (string)victim, ToucherID);
                llSay(0,llKey2Name(victim)+ " Your now secure locked!");
                
                llRlvSay("unsit=n");
                gMenu = gMenu2;
            }
            else
            {
                llRlvSay2("!release");
                victim = NULL_KEY;
                locker=NULL_KEY;
                llMessageLinked(LINK_THIS, gVic, (string)victim, ToucherID);
                llMessageLinked(LINK_THIS, gPlugin, "RESET", NULL_KEY);
            }            
        }  
    }
    
    touch_start(integer total_number)
    {
        ToucherID = llDetectedKey(0);
        if(victim==NULL_KEY)
        {
        	llSensor("", NULL_KEY, AGENT, range, PI);
        }
        else
        {
        	/*msg ="You have: " + llKey2Name(victim) +" locked on the Device";
        	gMenu=gMenu2;
        	displayMenu();*/
        	if(locker == NULL_KEY)
        	{
	       		//if(ToucherID!=victim)
	       		//{
		       		msg ="You have: " + llKey2Name(victim) +" on the Device";
	       			gMenu=gMenu2;
	       			displayMenu();
	       		//}
        	}
        	else if(locker==ToucherID)
        	{
        		msg ="You have: " + llKey2Name(victim) +" on the Device";
	       		gMenu=gMenu2;
	       		displayMenu();
        	}
        }
    }
    
    sensor(integer num)
    {
        //give menu of potential victims
        integer n;
        gMenu = [];
		objectKey=[];
		msg="";
        for (n = 0; n < num; ++n)
        {
        	objectKey+= llDetectedKey(n);
            msg +=(string)n+": "+ llDetectedName(n)+"\n";
            gMenu+=(string)n;
        }
        displayMenu();
    }
    
    link_message(integer sender, integer num, string str, key id)
  	{
  		if(num ==gMenuLink)
  		{
  			if(str==llGetScriptName())
  			{
  				llMessageLinked(LINK_THIS, gDemon, llGetScriptName(), NULL_KEY);
  				ToucherID=id;
		        if(victim==NULL_KEY)
		        {
		        	llSensor("", NULL_KEY, AGENT, range, PI);
		        }
		        else
		        {
		        	gMenu=gMenu2;
		        	displayMenu();
		        }
  			}
  		}

  		if(num ==gDemon)
  		{
  			if(str =="attachment")attachment=TRUE;
  			else if(str =="device")attachment=FALSE;
  			else if(str!=llGetScriptName())
  			{
				llListenRemove(listen_id);

  			}
  		}
  		if(num==gPlugin)
  		{
  			if(str=="ON_REZ")
  			{
  				
  			}
  			if(str=="RESET")
  			{
  				llRlvSay("unsit=y");
	  			llRlvSay("unsit=force"); 
	  			locker=NULL_KEY;
  			}
  		}

  	}
    
    timer()
    {
    	llListenRemove(listen_id);
    	llSetTimerEvent(0.0);
    }
}
